package backend;

import java.sql.*;
import java.util.Calendar;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TimeoutUsers extends TimerTask {
		
	private String timeoutQuery = "DELETE FROM online_user WHERE CURRENT_TIMESTAMP - ts > ";
	private Connection connection = null;
	private Statement stmt = null;
			
	public TimeoutUsers( int sec ) throws SQLException {
		timeoutQuery += sec;
	}
	
	@Override
	public void run() {
		try {
			if( connection == null || connection.isClosed() ) {
				connection = SqlConnection.getInstance().getConnection();
				stmt = connection.createStatement();
			}

			System.out.print(".");
			int num = stmt.executeUpdate(timeoutQuery);
			if( num > 0 ) {
				System.out.println("\n" + Calendar.getInstance().getTime() + ": " + num + " users has timeout from the server");
			}
			connection.close();
		} catch (SQLException ex) {
			Logger.getLogger(TimeoutUsers.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}